﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System
{
    public static class TypeExtension
    {
        public static bool IsNullable(this Type type)
        {
            return (!type.IsValueType) || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
        public static object GetDefault(this Type type)
        {
            return typeof(TypeExtension).GetMethod("GetDefaultValue").MakeGenericMethod(type).Invoke(null, new object[0]);
        }
        public static T GetDefaultValue<T>()
        {
            return default(T);
        }
        public static IEnumerable<T> Attributes<T>(this Type type) where T : Attribute
        {
            return GetAttributes<T>(type).Distinct();
        }
        private static IEnumerable<T> GetAttributes<T>(this Type type) where T : Attribute
        {
            do
            {
                foreach (var t in type.GetCustomAttributes(typeof(T), true).Cast<T>())
                    yield return t;
            } while ((type = type.BaseType) != null);
        }
    }
}
